package impl

import (
	"adam2/internal/domain"
	"adam2/internal/model"
	"anubis-framework/pkg/io"
)

type HisRobotAccountLogDaoImpl struct {
	*BaseDaoImpl
}

// 返回dao实现类
func GetHisRobotAccountLogDaoImpl() *HisRobotAccountLogDaoImpl {
	return &HisRobotAccountLogDaoImpl{GetBaseDaoImpl()}
}

// 返回表名
func (_hisRobotAccountLogDaoImpl *HisRobotAccountLogDaoImpl) FindTableName() string {
	return "HIS_ROBOT_ACCOUNT_LOG"
}

// 根据model_id字段，返回his_robot_account_log表中date_字段，并去重
func (_hisRobotAccountLogDaoImpl *HisRobotAccountLogDaoImpl) FindDistinctDateByModelIdOrderByDateAsc(modelId int) *[]string {
	io.Infoln("根据model_id[%d]字段，返回his_robot_account_log表中date_字段，并去重", modelId)

	var dateArray *[]string
	_hisRobotAccountLogDaoImpl.db.Raw("select distinct to_char(t.date_, 'yyyy-mm-dd') from his_robot_account_log t "+
		"where t.model_id=? order by to_char(t.date_, 'yyyy-mm-dd') asc",
		modelId).Scan(&dateArray)

	return dateArray
}

// 根据model_id字段，返回his_robot_account_log表中robot_name字段，并去重
func (_hisRobotAccountLogDaoImpl *HisRobotAccountLogDaoImpl) FindDistinctRobotNameByModelId(modelId int) *[]string {
	io.Infoln("根据model_id[%d]字段，返回his_robot_account_log表中robot_name字段，并去重", modelId)

	var robotNameArray *[]string
	_hisRobotAccountLogDaoImpl.db.Raw("select distinct t.robot_name from his_robot_account_log t where t.model_id=?",
		modelId).Scan(&robotNameArray)

	return robotNameArray
}

// 根据model_id字段，返回his_robot_account_log表中date_字段，按照date_升序排列，并去重
func (_hisRobotAccountLogDaoImpl *HisRobotAccountLogDaoImpl) FindByRobotNameAndModelIdOrderByDateAsc(modelId int, robotName string) model.HisRobotAccountLogArray {
	io.Infoln("根据robot_name[%s]、model_id[%d]字段返回记录，并按照date_字段升序排列", robotName, modelId)

	var hisRobotAccountLogArray model.HisRobotAccountLogArray
	_hisRobotAccountLogDaoImpl.db.Raw("select * from his_robot_account_log t where t.model_id=? and t.robot_name=? order by t.date_ asc",
		modelId, robotName).Scan(&hisRobotAccountLogArray)

	return hisRobotAccountLogArray
}

// 计算最大回撤
func (_hisRobotAccountLogDaoImpl *HisRobotAccountLogDaoImpl) CalculateMaximumDrawdown(modelId int) domain.MaximumDrawdownArray {
	io.Infoln("计算最大回撤，modelId为[%d]", modelId)

	var maximumDrwadownArray domain.MaximumDrawdownArray
	_hisRobotAccountLogDaoImpl.db.Raw("select * from ("+
		"select (t1.total_assets-t2.total_assets)/t1.total_assets*100 MAXIMUM_DRAWDOWN, "+
		"t1.date_ DATE1, t2.date_ DATE2, t1.robot_name ROBOT_NAME, t1.total_assets TOTAL_ASSETS1, "+
		"t2.total_assets TOTAL_ASSETS2 "+
		"from his_robot_account_log t1, his_robot_account_log t2 "+
		"where t1.model_id=? and t2.model_id=? and t1.robot_name=t2.robot_name and t1.date_<t2.date_ "+
		"order by (t1.total_assets-t2.total_assets)/t1.total_assets*100 desc) "+
		"where rownum<=10",
		modelId, modelId).Scan(&maximumDrwadownArray)

	return maximumDrwadownArray
}
